package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * 1248. 统计「优美子数组」
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/7 13:27
 */
public class NumberOfSubarrays {


    public static void main(String[] args) {
        NumberOfSubarrays test = new NumberOfSubarrays();


        // 2
//        int[] arr = {1, 1, 2, 1, 1};
//        int k = 3;

        // 0
//        int[] arr = {2,4,6};
//        int k = 1;

        // 16
        int[] arr = {2, 2, 2, 1, 2, 2, 1, 2, 2, 2};
        int k = 2;

        // 6
//        int[] arr = {1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 1, 1};
//        int k = 4;

        int i = test.numberOfSubarrays(arr, k);
        System.out.println(i);
    }

    public int numberOfSubarrays(int[] nums, int k) {
        int length = nums.length;
        int st = 0;
        while (st < length) {
            if ((nums[st] & 1) == 1) {
                break;
            }
            st++;
        }
        int item = st + 1;
        int end = st;
        int sum = 0;
        while (end < length) {
            if ((nums[end] & 1) == 1) {
                k--;
            }
            end++;
            if (k == 0) {
                sum = item;
                break;
            }
        }
        while (end < length) {
            if ((nums[end] & 1) == 1) {
                item = 1;
                while (st < end) {
                    st++;
                    if ((nums[st] & 1) == 1) {
                        break;
                    }
                    item++;
                }
            }
            sum += item;
            end++;
        }
        return sum;
    }

}
